<?php
/**
 * Created by PhpStorm.
 * User: syzhou
 * Date: 2019-08-28
 * Time: 14:48
 */

namespace App\Http\Controllers;


use App\Feedback;
use App\Project;
use App\ReviewerGroupProject;
use App\ReviewerGroupReviewer;
use App\ReviewerScoreProject;
use App\Services\ReviewerGroupService;
use App\Services\ReviewService;
use App\Services\WorkflowService;
use App\SysConfig;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Request;

class ReviewAPIController extends Controller
{
    private $reviewSvc;

    public function __construct()
    {
        $this->middleware('auth');
        $this->reviewSvc = new ReviewService();
    }

    public function getProjects()
    {
        $sysConfig = SysConfig::loadAll();
        $review_begin_at = $sysConfig['expert_review.begin_at'];
        $review_end_at = $sysConfig['expert_review.end_at'];
        $reviewEndDateCarbon = Carbon::createFromTimeString($review_end_at)->startOfDay();
        $currentDateCarbon = Carbon::now()->startOfDay();
        $remaining_days_for_review = max(0, $currentDateCarbon->diffInDays($reviewEndDateCarbon, false));

        $user = Request::user();
        $row = DB::table('reviewer_group_reviewers as a')
            ->where('a.reviewer_id', $user['id'])
            ->leftJoin('large_groups as b', 'a.large_group_id', '=', 'b.id')
            ->select('a.large_group_id', 'b.award_id')
            ->first();
        $if_attend_review = $row !== null;
        $data = [
            'if_attend_review' => $if_attend_review,
            'award_id' => $if_attend_review ? $row->award_id : null,
            'large_group_id' => $if_attend_review ? $row->large_group_id : null,
            'at_phase_expert_review' => false,
            'review_begin_at' => $review_begin_at,
            'review_end_at' => $review_end_at,
            'remaining_days_for_review' => $remaining_days_for_review,
            'projects' => [],
        ];
        if (!$if_attend_review) {
            return [
                'ok' => true,
                'code' => 0,
                'msg' => 'ok',
                'data' => $data,
            ];
        }
        try {
            $workflowSvc = new WorkflowService();
        } catch (\Exception $e) {
            return [
                'ok' => false,
                'code' => 3,
                'msg' => '构造 WorkflowService 实例失败'
            ];
        }

        $data['at_phase_expert_review'] = $workflowSvc->atPhases([WorkflowService::PHASE_EXPERT_REVIEW], $data['large_group_id']);
        if (!$workflowSvc->hasPhaseBegun(WorkflowService::PHASE_EXPERT_REVIEW, $data['large_group_id'])) {
            return $this->json([
                'ok' => true,
                'code' => 0,
                'msg' => 'ok',
                'data' => $data,
            ]);
        }
        $projectStatusIds = $workflowSvc->getProjectStatusesSincePhase(WorkflowService::PHASE_EXPERT_REVIEW);
        $projects = DB::table('reviewer_score_projects as a')
            ->where('a.reviewer_id', $user->id)
            ->leftJoin('applications as b', 'a.project_id', '=', 'b.id')
            ->whereIn('b.status_id', $projectStatusIds)
            ->leftJoin('users as c', 'b.user_id', '=', 'c.id')
            ->select('a.*', 'b.project_name', 'b.prof_category', 'c.name as applicant')
            ->orderBy('a.id', 'desc')
            ->get()->toArray();
        foreach ($projects as $project) {
            $project->score_status = ReviewerScoreProject::getScoreStatus($project);
        }
        $data['projects'] = $projects;
        return $this->json([
            'ok' => true,
            'code' => 0,
            'msg' => 'ok',
            'data' => $data,
        ]);
    }

    public function getProjectScore()
    {
        $user = Request::user();
        $reviewerId = $user->id;
        $projectId = Request::get('project_id');
        try {
            $reviewerScoreProject = ReviewerScoreProject::where('project_id', $projectId)
                ->where('reviewer_id', $reviewerId)
                ->first();
            if ($reviewerScoreProject === null) {
                return [
                    'ok' => false,
                    'code' => 3,
                    'msg' => 'Resource Not Found' . $projectId,
                ];
            }
            $reviewerScoreProject->form_data = json_decode($reviewerScoreProject->form_data, false);
            return [
                'ok' => true,
                'code' => 0,
                'msg' => 'ok',
                'reviewer_score_project' => $reviewerScoreProject
            ];
        } catch (\Exception $e) {
            Log::error('', ['exception' => $e]);
            return [
                'ok' => false,
                'code' => 2,
                'msg' => '数据库错误',
            ];
        }
    }

    public function saveProjectScore()
    {
        $user = Request::user();
        $data = Request::all();
        $data['reviewer_id'] = $user->id;
        $result = $this->reviewSvc->saveProjectScore($data);
        return $this->json($result);
    }

    public function submitProjectScore()
    {
        $user = Request::user();
        $projectId = Request::get('project_id');
        $result = $this->reviewSvc->submitProjectScore($user->id, $projectId);
        return $this->json($result);
    }

    public function submitFeedback()
    {
        $user = Request::user();
        Feedback::create([
            'status' => '未处理',
            'submitter_id' => $user->id,
            'feedback' => Request::get('content'),
            'created_at' => now(),
        ]);
        return $this->json(['ok' => true]);
    }

    public function reportWelcomeDialogShown()
    {
        $user = Request::user();
        $user->update(['welcome_dialog_shown' => true]);
        return $this->json(['ok' => true]);
    }

}